package org.shindou09.easytagforpage.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.shindou09.easytagforpage.Page;
import org.shindou09.easytagforpage.view.PageView;
import org.shindou09.easytagforpage.view.PageViewFactory;

public class PageTag extends TagSupport {

	private String url;
	private String name;
	private String scope="request";
	private String theme;

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getScope() {
		return scope;
	}

	public void setScope(String scope) {
		this.scope = scope;
	}

	public String getTheme() {
		return theme;
	}

	public void setTheme(String theme) {
		this.theme = theme;
	}
	
	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		JspWriter out = pageContext.getOut();
		String pv="ftl";
		if(pageContext.getServletContext().getInitParameter("pageView")!=null){
			pv=pageContext.getServletContext().getInitParameter("pageView");
		}
		PageView pageView = PageViewFactory.getPageView(pv);
		pageView.setTheme(theme);
		pageView.getView(helper(), url, out);
		return super.EVAL_PAGE;
	}
	
	private Page helper(){
		Page page=null;
		if(scope.equals("session")){
			page=(Page) pageContext.getSession().getAttribute(name);
		}else if(scope.equals("context")){
			page=(Page) pageContext.getServletContext().getAttribute(name);
		}else if(scope.equals("page")){
			page=(Page) pageContext.getAttribute(name);
		}else{
			page=(Page) pageContext.getRequest().getAttribute(name);
		}
		return page;
	}

}
